package com.zsummer.zero.hibernate;

import org.hibernate.Session;
import org.junit.Test;

/**
 * 一级缓存：session缓存，相关属性actionQueue，persistenceContext;
 * 缓存控制方法：
 * 	clear 清空一级缓存
 * 	evict 清空一级缓存中的指定对象
 * 	refresh 重新查询数据库，更新一级缓存与快照
 * @author zhouyujiang
 *
 */
public class Demo4 {
	
	/**
	 * 使用了session缓存，查询一次db，两次返回对象相同
	 */
	@Test
	public void run1() {
		Session session = HibernateUtils.openSession();
		session.getTransaction().begin();
		
		Person person = session.get(Person.class, 100);
		System.out.println(Integer.toHexString(person.hashCode()));
		
		Person person1 = session.get(Person.class, 100);
		System.out.println(Integer.toHexString(person1.hashCode()));
		
		session.getTransaction().commit();
		session.close();
		HibernateUtils.getsessionFactory().close();
	}
	
	/**
	 * session缓存被清除，查询了两次DB，返回的两个对象hash值不同
	 */
	@Test
	public void run2() {
		Session session = HibernateUtils.openSession();
		session.getTransaction().begin();
		
		Person person = session.get(Person.class, 100);
		System.out.println(Integer.toHexString(person.hashCode()));
		
		session.clear(); // 清除缓存
		
		Person person1 = session.get(Person.class, 100);
		System.out.println(Integer.toHexString(person1.hashCode()));
		
		session.getTransaction().commit();
		session.close();
		HibernateUtils.getsessionFactory().close();
	}
}
